//3．修改程序清单14.2中的图书目录程序，使其按照输入图书的顺序输出图书的信息，
//然后按照标题字母的升序输出图书的信息，最后按照价格的升序输出图书的信息。

/* manybook.c -- multiple book inventory */
#include <stdio.h>
#include <string.h>

char *s_gets(char *st, int n);

#define MAXTITL   40
#define MAXAUTL   40
#define MAXBKS   100              /* maximum number of books  */

struct book {                     /* set up book template     */
    char title[MAXTITL];
    char author[MAXAUTL];
    float value;
};

void sort_val(struct book arr[], int size);

void sort_title(struct book arr[], int size);
void show(struct book library[], int size);
int main(void) {
    struct book library[MAXBKS]; /* array of book structures */
    int count = 0;
    int index;

    printf("Please enter the book title.\n");
    printf("Press [enter] at the start of a line to stop.\n");
    while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL
           && library[count].title[0] != '\0') {
        printf("Now enter the author.\n");
        s_gets(library[count].author, MAXAUTL);
        printf("Now enter the value.\n");
        scanf("%f", &library[count++].value);
        while (getchar() != '\n')
            continue;          /* clear input line         */
        if (count < MAXBKS)
            printf("Enter the next title.\n");
    }

    if (count > 0) {
        show(library, count);
        sort_title(library, count);
        show(library, count);
        sort_val(library, count);
        show(library, count);
    } else
        printf("No books? Too bad.\n");

    return 0;
}

char *s_gets(char *st, int n) {
    char *ret_val;
    char *find;

    ret_val = fgets(st, n, stdin);
    if (ret_val) {
        find = strchr(st, '\n');   // look for newline
        if (find)                  // if the address is not NULL,
            *find = '\0';          // place a null character there
        else
            while (getchar() != '\n')
                continue;          // dispose of rest of line
    }
    return ret_val;
}

void sort_title(struct book arr[], int size) {
    for (int i = 0; i < size - 1; ++i) {
        for (int j = i; j < size; ++j) {
            if (strcmp(arr[i].title, arr[j].title) > 0) {
                struct book temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

void sort_val(struct book arr[], int size) {
    for (int i = 0; i < size - 1; ++i) {
        for (int j = i; j < size; ++j) {
            if (arr[i].value > arr[j].value) {
                struct book temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

void show(struct book library[], int size){
    printf("Here is the list of your books:\n");
    for (int index = 0; index < size; ++index) {
        printf("%s by %s: $%.2f\n", library[index].title,
               library[index].author, library[index].value);
    }
}

